package us.feng.tinyspring.beans;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanWrapperImpl implements BeanWrapper{
	
	private final Object beanObject;
	
	private final Class<?> beanObjectClass;
	
	public BeanWrapperImpl(Object object) {
		this.beanObject=object;
		beanObjectClass=beanObject.getClass();
	}

	@Override
	public void setPropertyValues(PropertyValues pvs) {
		PropertyValue []propertyValues=pvs.getPropertyValues();
		for(PropertyValue pv:propertyValues){
			setPropertyValue(pv);
		}
	}
	
	public void setPropertyValue(PropertyValue pv){
		
		Object originObject=pv.getValue();
		
		final Method writeMethod=resolveWriteMethod(pv,originObject);
		
		if(null==writeMethod|| null==originObject){
			return;
		}
		
		writeMethod.setAccessible(true);
		
		try {
			writeMethod.invoke(beanObject, originObject);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Method resolveWriteMethod(PropertyValue pv, Object object){
		String propertyName=pv.getName();
		String propertyWriteMethodName="set"+propertyName.substring(0, 1).toUpperCase()+propertyName.substring(1);
		Method method=null;
		try {
			method=this.beanObjectClass.getDeclaredMethod(propertyWriteMethodName,object.getClass());
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return method;
	}

	@Override
	public Object getBeanObject() {
		return this.beanObject;
	}

	@Override
	public Object getPropertyValue(String propertyName) throws BeanException {
		// TODO Auto-generated method stub
		return null;
	}

}
